import datetime

from flaskapp.exts import db


class Record(db.Model):
    __tablename__ = 'records'

    recordid = db.Column(db.Integer, primary_key=True)
    bookid = db.Column(db.Integer, nullable=False)
    startdate = db.Column(db.DateTime, nullable=False)
    loandays = db.Column(db.Integer, nullable=False)
    userid = db.Column(db.Integer, nullable=False)

    def __repr__(self):
        return f'<Record {self.recordid}, {self.startdate}, {self.loandays}, {self.userid}>'

    def __init__(self, bookid, startdate, loandays, userid):
        self.bookid = bookid
        self.startdate = startdate
        self.loandays = loandays
        self.userid = userid

    def to_dict(self):
        return {
            'recordid': self.recordid,
            'bookid': self.bookid,
            'startdate': self.startdate,
            'loandays': self.loandays,
            'userid': self.userid
        }

    def addPersonalRecord(self):
        db.session.add(self)
        db.session.commit()

    def addRecord(self):
        db.session.add(self)
        db.session.commit()

    def deleteRecord(self):
        db.session.delete(self)
        db.session.commit()

    def getExpireTime(self):
        return self.startdate + datetime.timedelta(days=self.loandays)
